import datetime
import threading
import time

import etcd3


class EtcdRegistry():
    def __init__(self, host, port, lease_ttl):
        self.cli = etcd3.Etcd3Client(host=host, port=port, user=None, password=None)
        self.ttl = lease_ttl
        self.lease = self.cli.lease(ttl=lease_ttl)

    def registry(self, service_name, address):
        self.cli.put(key=service_name, value=address, lease=self.lease)

    def keepalived(self):
        t = threading.Thread(target=self._keepalived, args=[self.lease])
        t.daemon = True
        t.start()

    def _keepalived(self, lease):
        while True:
            time.sleep(0.8 * self.ttl)
            resp = self.cli.refresh_lease(lease.id)
            list(resp)
            print(f"{datetime.datetime.now()}--refresh--")


if __name__ == '__main__':
    e = EtcdRegistry(host="127.0.0.1", port=2379)
    e.registry("user", "127.0.0.1:2369")
    e.keepalived()
    while True:
        pass
        # time.sleep(2)
        # print(e.cli.get_lease_info(e.lease.id))
        # resp = e.cli.refresh_lease(e.lease.id)
        # print(list(resp))
